// app.js
App({
    onLaunch() {
        // 登录
        this.miniapp_login();
        // 获取胶囊信息
        let menuButtonObject = wx.getMenuButtonBoundingClientRect();
        // console.log(menuButtonObject)
        // 获取设备信息
        wx.getSystemInfo({
            success: res => {
                this.globalData.platform = res.platform;
                // console.log(res.platform);
                // 整个导航栏的高度
                let navHeight = menuButtonObject.top + menuButtonObject.height + (menuButtonObject.top - res.statusBarHeight) * 2
                // 导航栏的高度
                let nav = navHeight - res.statusBarHeight
                // 挂载到全区变量 globalData 上
                this.globalData.navHeight = navHeight
                this.globalData.nav = nav
                // 胶囊与左边的距离
                this.globalData.menuLeft = menuButtonObject.left
                // 胶囊的高度
                this.globalData.menuHeight = menuButtonObject.height
                // 胶囊距离顶部的高度
                this.globalData.menuBot = menuButtonObject.top - res.statusBarHeight
                // 整个设备的宽度
                this.globalData.windowWidth = res.windowWidth
            },
            fail: err => {
                console.log(err)
            }
        })
    },
    data: {
        login_result: 0,
    },
    globalData: {
        userInfo: null,
        platform: false,
        // baseUrl: "http://qq.cn/",   // hjx本地环境 
        // baseUrl: "http://plmtest.panaryboy.cn/",   // scm测试环境 
        baseUrl: "https://plm.panaryboy.cn/",
        // alphaBaseUrl:"https://plm.panaryboy.cn/aef",

        //阿尔法接口地址
        alphaBaseUrl: wx.getAccountInfoSync().miniProgram.envVersion === 'release'?"https://plm.panaryboy.cn/aef"://正式服
        (wx.getAccountInfoSync().miniProgram.envVersion === 'trial'?"https://plm.panaryboy.cn/testaef"://体验版
        "https://plm.panaryboy.cn/aef"//本地
        ),
        alphaCdnUrl: "https://suoge-img.oss-cn-shenzhen.aliyuncs.com/scm",
    },
    // 同步获取系统信息
    get_system_info: function () {
        try {
            return wx.getSystemInfoSync();
        } catch (e) {
            return false;
        }
    },
    // 登录
    miniapp_login: function (is_show_tip = true) {
        let __this = this;
        // 获取系统信息
        var systemInfo = this.get_system_info();
        // 当前基础库版本号
        var now_version = 0;
        if (systemInfo) {
            now_version = parseInt(systemInfo.SDKVersion.replace(/\./g, ""));
        }
        // 调用登录接口
        wx.login({
            success(res) {
                if (res.code) {
                    // 发起网络请求
                    var result = __this.request_api('api/pro.User/miniAppLogin', {
                        code: res.code
                    }, is_show_tip);
                    result.then(res_data => {
                        // 保存token
                        try {
                            wx.setStorageSync('token', res_data.token);
                            wx.setStorageSync('user_id', res_data.userinfo.id);
                        } catch (e) {
                            wx.showToast({
                                title: '登录失败',
                                icon: 'none',
                                duration: 1500,
                            });
                            return false;
                        }
                        __this.data.login_result = 1;
                    });
                } else {
                    wx.showToast({
                        title: res.errMsg,
                        icon: 'none',
                        duration: 1500,
                    });
                }
            }
        })
    },
    // 验证是否登录
    check_is_login: function (is_show_tip = false, is_to_login = false) {
        var login_status = false;
        // 验证是否有token
        try {
            var value = wx.getStorageSync('token');
            if (value) {
                login_status = true;
            }
        } catch (e) {

        }
        // 跳转到登录
        if (is_to_login && !login_status) {
            this.miniapp_login();
        }
        // 返回
        return login_status;
    },
    // 发起请求 - 默认post
    request_api: function (url, req_data = {}, is_show_loading = true, req_method = 'POST',header_data={},is_return_res=false) {
        var __this = this;
        // 显示加载条
        if (is_show_loading) {
            wx.showLoading({
                title: '加载中',
                mask: true
            })
        }
        header_data = Object.assign({}, {
            "content-type": "application/json",
            "client-name":"wechat",
            "version-name":"1.2"
        },header_data);
        // 验证是否登录
        if (this.check_is_login()) {
            header_data = Object.assign({}, {
                "content-type": "application/json",
                'batoken': wx.getStorageSync('token'),
                "client-name":"wechat",
                "version-name":"1.2"
            },header_data);
        }
        // 发起请求
        return new Promise((resolve, reject) => {
            // 发起网络请求
            wx.request({
                url: __this.globalData.baseUrl + url,
                method: req_method,
                header: header_data,
                data: req_data,
                success(res2) {
                    // console.log(res2)
                    if (res2.statusCode == 200) {
                        if (res2.data.code == 1) {
                            // 解密
                            // var resolve_data = JSON.parse(Secret.decrypted(res2.data.data.code));
                            // 返回
                            if(is_return_res){
                                resolve(res2.data)
                            }else{
                                resolve(res2.data.data)
                            }
                            
                        } else if (res2.data.code == 0) {
                            setTimeout(function () {
                                wx.showToast({
                                    title: res2.data.msg,
                                    icon: 'none',
                                    duration: 2000,
                                });
                            }, 200)
                            reject(res2.data)
                        } else if (res2.data.code == 302) {
                            // 删除token
                            wx.removeStorage({
                                key: 'token'
                            });
                            // 登录失效重新登录
                            __this.miniapp_login();
                        } else if (res2.data.code == 401) {
                            // 无权操作
                            setTimeout(function () {
                                wx.showToast({
                                    title: res2.data.msg,
                                    icon: 'none',
                                    duration: 2000,
                                });
                            }, 200)
                        } else {
                            setTimeout(function () {
                                wx.showToast({
                                    title: res2.data.msg,
                                    icon: 'none',
                                    duration: 2000,
                                });
                            }, 200)
                            reject(res2.data);
                        }
                    } else if (res2.statusCode == 500) {
                        setTimeout(function () {
                            wx.showToast({
                                title: '系统错误',
                                icon: 'none',
                                duration: 2000,
                            });
                        }, 200)
                    }
                },
                fail: (err) => {
                    // 请求失败返回的消息
                    // reject(err)
                },
                complete() {
                    // 请求完做的事
                    if (is_show_loading) {
                        wx.hideLoading();
                    }
                }
            })
        })
    },

    // alpha 上传文件接口
    alpha_upload: function (   temp_file_path, is_show_loading = true) {
        console.log('上传文件接口temp_file_path',temp_file_path)
        const __this = this;
        // 验证是否登录
        if (!this.check_is_login(false, true)) {
            return false;
        }
        // 文件后缀
        var file_suffix = temp_file_path.substr(temp_file_path.lastIndexOf('.', temp_file_path)); 
        // 显示加载条
        if (is_show_loading) {
            wx.showLoading({
                title: '正在上传',
                mask: true
            });
        } 
        let  header_data = {  
            'Authorization': "Bearer " + wx.getStorageSync ('alpha_token'),
            "client-name": "wechat",
            "version-name": "1.2" 
        };  
        // 上传并返回
        return new Promise((resolve, reject) => { 
            wx.uploadFile({ 
                url: __this.globalData.alphaBaseUrl +  '/api/public/oss/original/uploadFace',
                header: header_data,
                filePath: temp_file_path,
                name: 'file',
                formData: {
                    
                },
                success(upRes) {
                    console.log("upRes",upRes)
                    // https://suoge-img.oss-cn-shenzhen.aliyuncs.com/scm/5283d34b0e4c41b9a5a8e4cf3adec286_1.png
                    if (upRes.statusCode == 200) {
                        let resData = JSON.parse(upRes.data);
                        var resolve_data = { 
                            file_path: `${__this.globalData.alphaCdnUrl}/${resData.data}` ,
                            file_key: resData.data,
                            file_suffix: file_suffix
                        }
                        resolve(resolve_data)
                    } else {
                        setTimeout(function () {
                            wx.showToast({
                                title: '系统错误',
                                icon: 'none',
                                duration: 2000,
                            });
                        }, 200)
                    }
                },
                fail(res) {
                    console.log(res)
                    setTimeout(function () {
                        wx.showToast({
                            title: '系统错误-fail',
                            icon: 'none',
                            duration: 2000,
                        });
                    }, 200)
                },
                complete() {
                    // 请求完做的事
                    if (is_show_loading) {
                        wx.hideLoading();
                    }
                }
            });
        });
    },

    // 上传文件接口
    request_upload: function (url, req_data = {}, temp_file_path, for_i, is_show_loading = true) {
        console.log('temp_file_path',temp_file_path)
        var __this = this;
        // 验证是否登录
        if (!this.check_is_login(false, true)) {
            return false;
        }
        // 文件后缀
        var file_suffix = temp_file_path.substr(temp_file_path.lastIndexOf('.', temp_file_path));
        // 日期
        var timestamp = Date.parse(new Date());
        var date = new Date(timestamp);
        var year = date.getFullYear();
        var month = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
        var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
        // 显示加载条
        if (is_show_loading) {
            wx.showLoading({
                title: '正在上传',
                mask: true
            });
        }
        var header_data = {};
        // 验证是否登录
        if (this.check_is_login()) {
            header_data = {
                batoken: wx.getStorageSync('token'),
            };
        }
        req_data.key = 'scm/' + year + month + day + '/' + this.create_uuid() + file_suffix;
        // 上传并返回
        return new Promise((resolve, reject) => {
            // 如果是旧文件则直接返回
            if (req_data.is_old_file != undefined && req_data.is_old_file == 1) {
                var resolve_data = {
                    for_i: for_i,
                    file_path: temp_file_path,
                    file_key: temp_file_path,
                    file_suffix: ''
                }
                resolve(resolve_data)
            }
            // 发起上传请求
            wx.uploadFile({
                // url: __this.globalData.baseUrl + url,
                url: 'https://up-z2.qiniup.com/?uuid=' + this.create_uuid(),
                header: header_data,
                filePath: temp_file_path,
                name: 'file',
                formData: {
                    key: req_data.key,
                    token: req_data.token
                },
                success(res2) {
                    if (res2.statusCode == 200) {
                        JSON.parse(res2.data);
                        var resolve_data = {
                            for_i: for_i,
                            file_path: req_data.cdn_url + req_data.key,
                            file_key: req_data.key,
                            file_suffix: file_suffix
                        }
                        resolve(resolve_data)
                    } else if (res2.statusCode == 500) {
                        setTimeout(function () {
                            wx.showToast({
                                title: '系统错误',
                                icon: 'none',
                                duration: 2000,
                            });
                        }, 200)
                    }
                },
                fail(res) {
                    console.log(res)
                },
                complete() {
                    // 请求完做的事
                    if (is_show_loading) {
                        wx.hideLoading();
                    }
                }
            });
        });
    },

    // 生成uuid
    create_uuid: function () {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = Math.random() * 16 | 0,
                v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    },

    // 设置监听器
    watch: function (ctx, obj) {
        Object.keys(obj).forEach(key => {
            this.observer(ctx.data, key, ctx.data[key], function (value) {
                obj[key].call(ctx, value)
            })
        })
    },

    // 监听属性，并执行监听函数
    observer: function (data, key, val, fn) {
        Object.defineProperty(data, key, {
            configurable: true,
            enumerable: true,
            get: function () {
                return val
            },
            set: function (newVal) {
                if (newVal === val) return
                fn && fn(newVal)
                val = newVal
            },
        })
    }


})
